#include "gas-plume.h"
#include "random_gen.h"
#include "rockdodger_globals.h"
#include <assert.h>
#include <math.h>
#include <SDL/SDL_video.h>

#define MAX_PLUMEDOTS 0x0700
#define PLUMEDOTS_END (plumedots + MAX_PLUMEDOTS)
#define PLUME_SHIFTVAL (1 << PLUME_SHIFT)

static gasdot_t plumedots[MAX_PLUMEDOTS];
static gasdot_t *plumedots_end = plumedots;

void reset_plumedots(void) {
  plumedots_end = plumedots;
}

void create_plumedots(int num, short x, short y, short heading, short angle, float speed) {
  while(--num > 0 && plumedots_end < PLUMEDOTS_END - 1) {
    float fheading = heading + (rnd() - 0.5) * angle;
    float speed_ = speed * (0.3 + 0.7 * rnd());

    ++plumedots_end;
    fheading *= 2 * M_PI / 360.0;
    plumedots_end->x = x + (rnd() - 0.5) * 4;
    plumedots_end->x <<= PLUME_SHIFT;
    plumedots_end->y = y + (rnd() - 0.5) * 4;
    plumedots_end->y <<= PLUME_SHIFT;
    plumedots_end->dx = cosf(fheading) * speed_ * PLUME_SHIFTVAL;
    plumedots_end->dy = -sinf(fheading) * speed_ * PLUME_SHIFTVAL;
    plumedots_end->life = (0.05 * rnd() + 0.95) * PLUME_SHIFTVAL;
  }
}

void draw_plumedots(SDL_Surface *surf) {
  gasdot_t *dotptr;
  int x, y;
  RD_VIDEO_TYPE *rawpixel;
  gasdot_t *targetptr = plumedots;

  rawpixel = (RD_VIDEO_TYPE *) surf->pixels;
  for(dotptr = plumedots; dotptr < plumedots_end; ++dotptr) {
    targetptr->life = dotptr->life - movementrate * PLUME_SHIFTVAL / 63.0;
    targetptr->x = dotptr->x + dotptr->dx * movementrate;
    targetptr->y = dotptr->y + dotptr->dy * movementrate;
    x = targetptr->x >> PLUME_SHIFT;
    y = targetptr->y >> PLUME_SHIFT;
    if(targetptr->life > 0 && y >= 0 && y < ysize && x >= 0 && x < xsize) {
      //I think copying is faster than testing if targetptr != dotptr.
      targetptr->dx = dotptr->dx;
      targetptr->dy = dotptr->dy;
      int32_t col_R = 220 * targetptr->life;
      int32_t col_G = targetptr->life < PLUME_SHIFTVAL / 2 ? 15 + ((220 * targetptr->life * 2) >> PLUME_SHIFT) : 255;
      int32_t col_B = targetptr->life < PLUME_SHIFTVAL / 2 ? 150 + ((105 * targetptr->life * 2) >> PLUME_SHIFT) : 255;
      col_R >>= PLUME_SHIFT;
      assert(col_R < 256);
      assert(col_G < 256);
      assert(col_B < 256);
      rawpixel[surf->pitch / sizeof(RD_VIDEO_TYPE) * y + x] =
	SDL_MapRGB(surf->format, col_R, col_G, col_B);
#if 0 //def DEBUG
      printf("x=$%X y=$%X dx=$%X dy=$%X life=$%hX\n", targetptr->x, targetptr->y, targetptr->dx, targetptr->dy, targetptr->life);
#endif
      ++targetptr;
      assert(targetptr < PLUMEDOTS_END);
    }
  }
  plumedots_end = targetptr;
}
